package internationalenergytradingplatform.controller.BuyerController;

import internationalenergytradingplatform.VO.OrderPageQueryVO;
import internationalenergytradingplatform.context.BaseContext;
import internationalenergytradingplatform.controller.SupplierController.HomeController;
import internationalenergytradingplatform.dao.BuyerAccountDao;
import internationalenergytradingplatform.dao.CommodityDao;
import internationalenergytradingplatform.dao.OrderMapper;
import internationalenergytradingplatform.dao.SupplierAccountDao;
import internationalenergytradingplatform.pojo.BuyerAccount;
import internationalenergytradingplatform.pojo.BuyerBalance;
import internationalenergytradingplatform.pojo.Commodity;
import internationalenergytradingplatform.pojo.Order;
import internationalenergytradingplatform.result.Result;
import internationalenergytradingplatform.service.OrderService;
import internationalenergytradingplatform.utils.MessageUtils;
import internationalenergytradingplatform.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.Session;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 名称BuyerOrderController
 * 描述
 *
 * @version 1.0
 * @author:DuanMM
 * @datatime:2024-03-24 22:40
 */
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/buyer-order")
public class BuyerOrderController {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    CommodityDao commodityDao;

    @Autowired
    BuyerAccountDao buyerAccountDao;

    @Autowired
    WebSocketServer webSocketServer;

    @Autowired
    MessageUtils messageUtils;

    @Autowired
    HomeController homeController;

    @Autowired
    SupplierAccountDao supplierAccountDao;

    @Autowired
    OrderService orderService;

    /**
     *计算运费
     */
    @PostMapping("calculateShippingCosts")
    public Result calculateShippingCosts(Integer commodityId) {
        String buyer = BaseContext.getCurrentId();
        Double shippingCosts = orderService.calculateShippingCosts(commodityId, buyer);
        return Result.success(shippingCosts);
    }

    /**
     * 新增订单
     */
    @PostMapping("/addOrder")
    public Result addOrder(@RequestBody Order order) {
        //检查库存是否充足
        Integer commodityId = order.getCommodity();
        Commodity commodityById = commodityDao.getCommodityById(commodityId);
        double inventory = commodityById.getInventory();
        if(order.getNumber() > inventory){
            return Result.error("库存不足");
        }
        //检查余额是否充足
        String buyer = BaseContext.getCurrentId();
        BuyerAccount buyerByTele = buyerAccountDao.getBuyerByTele(buyer);
        double totalAmount = order.getNumber() * commodityById.getPrice();
        if(buyerByTele.getBalance() < totalAmount){
            return Result.error("余额不足，请先充值！");
        }
        // 设置订单时间为当前时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        order.setOrderTime(formattedDateTime);
        //设置供应商
        order.setSupplier(commodityById.getSupplierAccount());
        //设置采购商
        order.setBuyer(buyer);
        //设置订单状态
        order.setStatus(1);
        //设置订单运费
        Double shippingCosts = orderService.calculateShippingCosts(commodityId, buyer);
        order.setFreight(shippingCosts);
        //更新余额
        buyerAccountDao.updateBalance(buyerByTele.getBalance() - totalAmount, buyer);
        //增加供应商余额
        supplierAccountDao.savingMoney(formattedDateTime, totalAmount, commodityById.getSupplierAccount());
        //更新库存
        commodityDao.updateInventory(inventory - order.getNumber(), order.getCommodity());
        // 调用mapper的添加订单方法
        log.info("添加订单信息：{}", order);
        //增加订单
        orderMapper.addOrder(order);
        //记录余额流水
        BuyerBalance buyerBalance = new BuyerBalance();
        buyerBalance.setTime(formattedDateTime);
        buyerBalance.setType(4);
        buyerBalance.setBalance(totalAmount);
        buyerBalance.setSource(order.getId());
        buyerBalance.setAccount(buyer);
        //向浏览器发送websocket
        webSocketServer.sendToAllClient("有新用户下单：" + DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
        return Result.success("你的已下单" + order.getNumber() + commodityById.getUnitInventory() +
                commodityById.getName() + "，余额还剩：" + buyerByTele.getBalance() + "k");
    }

    /**
     *
     * @author yingfeng
     * @date 2024/3/25 21:25
     发送验证码
     */
    @PostMapping("sendSMS/{tele}")
    public Result sendSMS(@PathVariable String tele) throws Exception {
        //发送验证码
        String sendSMS = messageUtils.sendSMS(tele, "11032");
        log.info(sendSMS);
        return Result.success(sendSMS);
    }

    /**
     *
     * @author yingfeng
     * @date 2024/3/25 21:46
     验证验证码是否正确
     */
    @PostMapping("/book/{tele}/{code}")
    public Result verificationCode(@PathVariable String tele, @PathVariable String code){
        boolean validateSMS = messageUtils.validateSMS(tele, code);
        log.info("验证的结果是：{}", validateSMS);
        if(validateSMS){
            return Result.success();
        }
        return Result.error("验证码有误！");
    }

    /**
     * 根据token返回采购商信息
     */
    @GetMapping("/buyer")
    public Result getBuyerByToken(){
        String tele = BaseContext.getCurrentId();//获取buyerid
        BuyerAccount buyerByTele = buyerAccountDao.getBuyerByTele(tele);
        return Result.success(buyerByTele);
    }

    /**
     * 关闭websocket连接
     */
    @GetMapping("/closeWebSocket")
    public Result closeWebSocket(String token){
        log.info("关闭websocket连接:{}", token);
        //更新redis营业状态
        homeController.turnBusinessStatus();
        webSocketServer.onClose(token);
        return Result.success();
    }

    /**
     *
     * @author yingfeng
     * @date 2024/3/29 13:01
     建立webscoket连接
     */
    @GetMapping("/openWebSocket")
    public Result openWebSocket(){
        //更新redis营业状态
        homeController.turnBusinessStatus();
        return Result.success();
    }

    /**
     *
     * @author yingfeng
     * @date 2024/4/30 23:08
     查询自己下单的所有订单
     */
    @GetMapping("/getAllOrderByOwn")
    public Result getAllOrderByOwn(){
        String buyer = BaseContext.getCurrentId();
        List<OrderPageQueryVO> allOrderByOwn = orderMapper.getAllOrderByOwn(buyer);
        return Result.success(allOrderByOwn);
    }

    /**
     *
     * @author yingfeng
     * @date 2024/5/1 15:46
     签收订单
     */
    @PutMapping("/signForOrder")
    public Result signForOrder(Integer orderId){
        orderMapper.signForOrder(orderId);
        return Result.success();
    }
}
